<?php

/**
 * This class manages all database queries (or other operations)
 * concerning users, including login and logout.
 */
class Model_User extends Model_Person
{    
    /**
     * Lists all user, ordered alphabetically by name.
     * 
     * @return array an array of (associative) arrays
     */
    public function listAll($where = "person_type = 'Mitarbeiter' AND (expire_date is null or expire_date > now())")
    {
	return parent::listAll($where);
    }
    
    public function listInactive($where = "person_type = 'Mitarbeiter' AND (expire_date is not null AND expire_date <= now())")
    {
	return parent::listAll($where);
    }
    
    /**
     * Persists a new user to the database.
     * 
     * @param array $user the user's data
     */
    public function create($user)
    {
	$user['person_type'] = 'Mitarbeiter';
	$salt = $this->createSalt();
	$pwdEntry = array(
	    'salt' => $salt,
	    'password' => $this->encryptPassword($user['password'], $salt)
	);

	$mail = $user;
	unset($user['password']);
	$this->db->insert($this->name, $user);
	
	$id = $this->db->lastInsertId($this->name);
	$pwdEntry['idperson'] = $id;

	$this->db->insert('password', $pwdEntry);
	try
	{
	    $this->sendMail($mail, $user);
	}catch (Exception $e)
	{
	    echo "Die E-Mail konnte nicht versandt werden.";
	}
    }
    
    /**
     * Updates a user's data.
     * 
     * @param array $user the user's data
     */
    public function update(array $user)
    {
	$where = $this->db->quoteInto('id = ?', $user['id']);
	$this->db->update($this->name, $user, $where);
    }
    
    /**
     * Get a user's data. The user is identified by its id.
     * 
     * @param type $id the user's id
     * @return array the user's data, or FALSE if not found
     */
    public function find($id)
    {
	$select = $this->db->select()
		->from($this->name)
		->where('id = ?', $id);
	return $this->db->fetchRow($select);
    }
    
    /**
     * Removes a user from the database identified by its id.
     * 
     * @param type $id the user's id
     */
    public function delete($id)
    {
	$user_where = $this->db->quoteInto('id = ?', $id);
	$worktime_where = $this->db->quoteInto('idperson = ?', $id);
	$password_where = $this->db->quoteInto('idperson = ?', $id);
	
	$this->db->delete('worktime', $worktime_where);
	$this->db->delete('password', $password_where);
	$this->db->delete($this->name, $user_where);
    }
    
     /**
     * Removes a user from the database identified by its id.
     * 
     * @param type $id the user's id
     */
    public function deleteAll()
    {
	$this->db->delete($this->name); 
    }
    
    public function changePw(array $password)
    {
	$user = Zend_Auth::getInstance()->getIdentity();
	$where = $this->db->quoteInto('idperson = ?', $user['idperson']);
	
	$select = $this->db->select()
		->from(array('u' => 'person'))
		->join(array('p' => 'password'), 'u.id = p.idperson')
		->where('u.email = ?', $user['email']);
	
	$pw = $this->db->fetchRow($select);
	if($pw)
	{
	    $pwdEncr = $this->encryptPassword($password['old_password'], $pw['salt']);
	    if($pwdEncr == $pw['password'])
	    {
		unset($pw['password']);
		$salt = $this->createSalt();
		$newPwEntry = array(
				'salt' => $salt,
				'password' => $this->encryptPassword($password['password'], $salt)
		);
		if($this->db->update('password', $newPwEntry, $where))
		{
		    //$this->sendMail($password['password']);
		}
	    }
	    else
	    {
		$this->logout();
	    }
	}
	else
	{
	    $this->logout();
	}
    }
    
    private function sendMail($newPassword, $user)
    {
	$mailConfig = Zend_Registry::get('config');

	$config = array(
			'ssl' => $mailConfig->mail->ssl,
			'port' => $mailConfig->mail->port,
			'auth' => $mailConfig->mail->auth,
			'username' => $mailConfig->mail->username,
			'password' => $mailConfig->mail->password);

	$transport = new Zend_Mail_Transport_Smtp($mailConfig->mail->host, $config);

	$body = "Hallo " . $newPassword['forename'] . ",<br /><br />" . 
		"du wurdest als neuer Benutzer der flexiblen Kinderbetreuung hinzugef&uuml;gt.<br />" .
		"Anbei findest du die Daten mit denen du angemeldet wurdest.<br /><br />" .
		"Vorname: " . $newPassword['forename'] . "<br />" .
		"Nachname: " . $newPassword['surname'] . "<br />" .
		"E-Mail: " . $newPassword['email']. "<br />" .
		"Telefon: " . $newPassword['telnumber'] . "<br />" .
		"Arbeitsform: " . $newPassword['form_of_employment'] . "<br />" .
		"Passwort: " . $newPassword['password'] . "<br /><br />" .
		"Mit freundlichen Gr&uuml;&szlig;en <br />FKB (Flexible Kinderbetreuung)";
	
	$mail = new Zend_Mail();
	$mail->setBodyText($body);
	$mail->setBodyHtml($body);
	$mail->setFrom('fkinderbetreuung@gmail.com', 'Flexible Kinderbetreuung');
	$mail->addTo($user['email'], $user['forename'] . " " . $user['surname']);
	$mail->setSubject('Du wurdest als neuer Benutzer der flexiblen Kinderbetreuung hinzugefuegt');
	$mail->send($transport);
    }
    
    /**
     * Creates a new, unique salt value.
     * 
     * @return String the new salt value
     */
    public function createSalt() {
	return sha1(rand());
    }
    
    /**
     * Encrypts a password, including a salt value.
     * 
     * @param type $clearText the password to encrypt
     * @param type $salt the salt value
     * @return String the encrypted password
     */
    public function encryptPassword($clearText, $salt) {
	return sha1($salt . sha1($salt . $clearText));
    }
    
    /**
     * Checks if a user is logged in.
     * 
     * @return boolean true if user is logged in, false otherwise.
     */
    public function isLoggedIn() 
    {
	return Zend_Auth::getInstance()->hasIdentity();
    }
    
    /**
     * Try to login a user.
     * 
     * Writes user data to Zend_Auth.
     * 
     * @param array $data the login credentials (email and password).
     */
    public function login(array $data) 
    {
	$select = $this->db->select()
		->from(array('u' => 'person'))
		->join(array('p' => 'password'), 'u.id = p.idperson')
		->where('u.email = ?', $data['email'])
		->where('expire_date IS NULL OR expire_date > now()');
	
	$user = $this->db->fetchRow($select);
	
	if($user)
	{
	    $pwdEncr = $this->encryptPassword($data['password'], $user['salt']);
	    if($pwdEncr == $user['password'])
	    {
		unset($user['password']);
		$user['role'] = ($user['is_admin'] == 'Y') ? 'admin' : 'user';
		Zend_Auth::getInstance()->getStorage()->write($user);
	    }
	    else
	    {
		$this->logout();
	    }
	}
	else
	{
	    $this->logout();
	}
    }
    
    /**
     * Logs out a user.
     * 
     * Clears Zend_Auth.
     */
    public function logout()
    {
	Zend_Auth::getInstance()->clearIdentity();
    }

    /**
     * 
     * Set a valid date to expire_date column in person table
     * 
     * @param type $id
     */
    public function setInaktiv($id)
    {		
	$date = new Zend_Date();
	$date->sub(1, Zend_Date::SECOND);
	$date_now= $date->get('YYYY-MM-dd HH:mm:ss'); 
	$this->db->update($this->name, array('expire_date' => $date_now), array('id = ?' => $id));	
    }
    
    /**
     * remove a date from the expire_date column in person table
     * 
     * @param type $id
     */
    public function setaktiv($id)
    {
	$this->db->update($this->name, array('expire_date' => null), array('id = ?' => $id));
    }
    
}